//
//  KBHomeViewController.swift
//  KimboWeiBoSwift
//
//  Created by kimbo on 15/12/15.
//  Copyright © 2015年 kimbo. All rights reserved.
//

import UIKit
import SVPullToRefresh
import SVProgressHUD

/// cellID枚举标识
enum KBStatusCellReuseIdentifier: String {
    case normalCell = "statusNormalCell" /// 原创微博
    case forwardCell = "statusForwardCell" /// 转发微博
}

class KBHomeViewController: KBBaseViewController {

    // MARK: - 属性
    /// 重用标识
    private let ReuseIdentifier = "homeViewCell"
    
    /// 提示刷新多少条微博的view的高度
    private let tipLabelHeight: CGFloat = 44
    
    /// 所有微博的数组
    var statuses: [KBStatus]? {
        didSet {
            self.tableView.reloadData() //刷新
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 判断用户是否登录
        if !KBUserAccount.userLogin {
            return
        }
        
        setupTableView()
        
        //设置导航栏
        setupNav()

        setupRefreshControl()
    }
    
    /// 设置refreshControl
    private func setupRefreshControl() {
        refreshControl = KBRefreshControl()

        refreshControl?.addTarget(self, action: "loadNewStatus", forControlEvents: UIControlEvents.ValueChanged)
        
        //进入程序显示刷新菊花
        refreshControl?.beginRefreshing()
        
        //主动触发UIControlEvents.ValueChanged事件
        refreshControl?.sendActionsForControlEvents(UIControlEvents.ValueChanged)
    }
    
    /// 下拉刷新微博
    @objc private func loadNewStatus() {
        
        let since_id = statuses?.first?.id ?? 0 //新微博数据
        let max_id = 0 //旧微博数据
        
        KBStatus.loadStatus(since_id, max_id: max_id) { (statuses, error) -> () in
            //结束刷新
            self.refreshControl?.endRefreshing()
            
            if error != nil {
                return
            }
            
            let count = statuses?.count ?? 0
            
            if since_id > 0 {//不是第一次进入程序，下拉刷新显示提示View
                self.showTipView(count)
            }
            
            if count == 0 {
                return
            }
            
            if since_id > 0 { //下拉刷新，赋值刷新的微博+已有微博
                self.statuses = statuses! + self.statuses!
            } else { //第一次进入程序,赋值20条微博
                self.statuses = statuses
                //第一次进入程序后显示上拉加载更多菊花
                self.tableView.showsInfiniteScrolling = true
            }
        }
    }
    
    /// 下拉刷新显示提示View
    private func showTipView(count: Int) {
        navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
        tipLabel.text = count == 0 ? "没有加载到新微博数据" : "加载了\(count)条新微博数据"
        
        UIView.animateWithDuration(1.25, animations: { () -> Void in
            self.tipLabel.frame.origin.y = self.tipLabelHeight
            }) { (_) -> Void in
                UIView.animateWithDuration(1.25, delay: 0.5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                    self.tipLabel.frame.origin.y = -(self.tipLabelHeight + 20)
                    }, completion: nil)
        }
    }
    
    /// 设置UI
    private func setupTableView() {
        //注册cell
        // 原创微博
        tableView.registerClass(KBStatusNormalCell.self, forCellReuseIdentifier: KBStatusCellReuseIdentifier.normalCell.rawValue)
        // 转发微博
        tableView.registerClass(KBStatusForwardCell.self, forCellReuseIdentifier: KBStatusCellReuseIdentifier.forwardCell.rawValue)
        
        // cell的预高:有了它，就不会一次性将所以的cell高计算出来，而是(如果预高为200，屏幕高度为667，那么就会计算四个cell高，然后出现一个计算一个，直到计算完所以的cell高为止)
        tableView.estimatedRowHeight = 200
        //        tableView.rowHeight = UITableViewAutomaticDimension
        
        //去掉分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        //添加第三方在最后一个cell上拉加载更多控件
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            self.loadMoreStatus()
        }
        //先不显示上拉菊花，等第一次进入程序后上拉再显示
        tableView.showsInfiniteScrolling = false
    }
    
    /// 上拉加载更多微博
    @objc private func loadMoreStatus() {
        let since_id = 0 //新微博数据
        let max_id = statuses?.last?.id ?? 0 //旧微博数据
        
        KBStatus.loadStatus(since_id, max_id: max_id) { (statuses, error) -> () in
            //结束加载更多
            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil {
                SVProgressHUD.showErrorWithStatus("上拉刷新数据失败")
                return
            }
            
            let count = statuses?.count ?? 0
            if count == 0 {
                return
            }
            
            if max_id > 0 { //加载到更多数据
                self.statuses = self.statuses! + statuses!
            }
        }
    }
    
    private func setupNav() {
        // 左
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch")
        // 右
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
        // 中
        // ??代表前面可选有值时用可选，没值时用后面
        let title = KBUserAccount.loadUserAccount()?.screen_name ?? "新浪微博"
        let btn = KBHomeTitleButton(title: title, imageName: "navigationbar_arrow_down")
        btn.addTarget(self, action: "titleViewDidClick:", forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = btn
    }

    /// 点击titleView，旋转箭头
    @objc private func titleViewDidClick(btn: UIButton) {
        
        btn.selected = !btn.selected
        
        UIView.animateWithDuration(0.25) { () -> Void in
            btn.imageView!.transform = btn.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI) - 0.001) : CGAffineTransformIdentity
        }
    }
    
    // MARK: - tableView数据源和代理方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let status = statuses![indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(status.cellID(), forIndexPath: indexPath) as! KBStatusCell
        
        cell.status =  status//响应微博数据
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        let status = statuses![indexPath.row]
        
        //1 先去模型中找cell高(不然每一次都计算一次会很消耗性能)
        if status.rowHeight != nil {
            return status.rowHeight!
        }
        
        //2 没有缓存，再计算cellHeight
        let cell = tableView.dequeueReusableCellWithIdentifier(status.cellID()) as!KBStatusCell
        
        let rowHeight = cell.calcCellHeight(status)
        status.rowHeight = rowHeight //缓存rowHeight
        
        return rowHeight
    }
    
    // MARK: - 属性
    /* 显示刷新多少条微博的view */
    private lazy var tipLabel: UILabel = {
       let tipLabel = UILabel(frame: CGRect(x: 0, y: -(self.tipLabelHeight + 20), width: UIScreen.mainScreen().bounds.width, height: self.tipLabelHeight))
        
        tipLabel.backgroundColor = UIColor.orangeColor()
        tipLabel.textColor = UIColor.whiteColor()
        tipLabel.textAlignment = NSTextAlignment.Center
        tipLabel.font = UIFont.systemFontOfSize(16)
        
        return tipLabel
    }()
    
}
